import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:get/get.dart' as Get;

import '../service/auth_service.dart';
import 'logger.dart';

 const String APP_VERSION = "20250213";
 const String CLIENT_PLATFORM = "android";
 const String APP_ENV = "ideaflow";

class HttpManager {
  Dio? _dio;

  static final HttpManager _instance = HttpManager._internal();

  factory HttpManager() => _instance;

  HttpManager._internal() {
    BaseOptions options = BaseOptions(
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 10),
    );
    _dio = Dio(options);

    _dio?.httpClientAdapter = IOHttpClientAdapter(createHttpClient: () {
      HttpClient client = HttpClient();
      client.badCertificateCallback = (X509Certificate cert, String host, int port) {
        return true;
      };
      return client;
    });

    _dio?.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        print(options.headers);
        return handler.next(options);
      },
      onResponse: (response, handler) {
        return handler.next(response); // 继续传递响应
      },
      onError: (DioError e, handler) {
        return handler.next(e);
      },
    ));
  }

  Future get(String url, {Map<String, dynamic>? params}) async {
    try {
      logger.d("get url=$url");
      final authService = Get.Get.find<AuthService>();
      var token = authService.userModel?.token ?? "";

      var headers = <String, dynamic>{};
      headers["authorization"] = "metatube-$token";
      headers["uid"] = authService.userModel?.uid ?? "";
      headers["env"] = APP_ENV;
      headers["c"] = CLIENT_PLATFORM;
      headers["pg"] = "10";
      headers["version"] = APP_VERSION;
      final options = Options(headers: headers);

      Response? response = await _dio?.get(url, queryParameters: params, options: options);
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  // POST 请求
  Future post(String url, {Map<String, dynamic>? params}) async {
    try {
      logger.d("get url=$url");
      final authService = Get.Get.find<AuthService>();
      var token = authService.userModel?.token ?? "";

      var headers = <String, dynamic>{};
      headers["Content-Type"] = "application/json";
      headers["authorization"] = "metatube-$token";
      headers["uid"] = authService.userModel?.uid ?? "";
      headers["env"] = APP_ENV;
      headers["c"] = CLIENT_PLATFORM;
      headers["pg"] = "10";
      headers["version"] = APP_VERSION;
      final options = Options(headers: headers);

      Response? response = await _dio?.post(url, data: params, options: options);
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future uploadAudio(String url, String filePath) async {
    try {
      FormData formData = FormData.fromMap({
        "mFile": await MultipartFile.fromFile(
          filePath,
          filename: "audio.wav",
          contentType: DioMediaType("audio", "mpeg"),
        ),
        "keyPath": "whisper/"
      });

      var headers = <String, dynamic>{};
      headers["Content-Type"] = "multipart/form-data";
      headers["Accept"] = "application/json";

      final authService = Get.Get.find<AuthService>();
      if (authService.userModel != null) {
        var token = authService.userModel?.token ?? "";
        headers["authorization"] = "metatube-$token";
        headers["uid"] = authService.userModel?.uid ?? "";
      }
      headers["env"] = APP_ENV;
      headers["c"] = CLIENT_PLATFORM;
      headers["pg"] = "10";

      final options = Options(headers: headers);
      Response? response = await _dio?.post(url, data: formData, options: options);
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  Future uploadImage(String url, File imageFile) async {
    try {
      FormData formData = FormData.fromMap({
        "mFile": await MultipartFile.fromFile(
          imageFile.path,
          filename: "mFile.jpeg",
          contentType: DioMediaType("image", "jpeg"),
        ),
      });

      var headers = <String, dynamic>{};
      headers["Content-Type"] = "multipart/form-data";
      headers["Accept"] = "application/json";

      final authService = Get.Get.find<AuthService>();
      if (authService.userModel != null) {
        var token = authService.userModel?.token ?? "";
        headers["authorization"] = "metatube-$token";
        headers["uid"] = authService.userModel?.uid ?? "";
      }
      headers["env"] = APP_ENV;
      headers["c"] = CLIENT_PLATFORM;
      headers["pg"] = "10";

      final options = Options(headers: headers);
      Response? response = await _dio?.post(url, data: formData, options: options);
      return response;
    } on DioException catch (e) {
      _handleError(e);
      rethrow;
    }
  }

  // 处理错误
  void _handleError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        logger.e("Connection Timeout Exception");
        break;
      case DioExceptionType.sendTimeout:
        logger.e("Send Timeout Exception");
        break;
      case DioExceptionType.receiveTimeout:
        logger.e("Receive Timeout Exception");
        break;
      case DioExceptionType.badCertificate:
        logger.e("Bad Certificate Exception");
        break;
      case DioExceptionType.badResponse:
        logger.e("Received invalid status code: ${error.response?.statusCode}");
        break;
      case DioExceptionType.cancel:
        logger.e("Request to API server was cancelled");
        break;
      case DioExceptionType.connectionError:
        logger.e("Connection Error Exception");
        break;
      case DioExceptionType.unknown:
        logger.e("Unexpected error: ${error.message}");
        break;
    }
  }
}
